package org.mashart.pink.m.store;

import java.util.Hashtable;
import java.util.Enumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStoreException;

/**
 * Manage all user configurable preferences of the application.
 * @author peng
 */
public class Preferences {

    /**
     * Key of a parameter
     */
    public static final String vYes = "Y";
    public static final String vNo = "N";
    
    public static final String kUser = "user";
    public static final String kPath = "path";
    public static final String kUrl = "url";

    public static final String kDeviceType = "devType";
    public static final String kBtConnectionURL = "btUrl";
    public static final String vBuiltin = "built-in";
    public static final String vBluetooth = "bluetooth";

    public static final String kWsConnector = "wsconn";
    public static final String kSendInterval = "sdItvl";
    public static final String kConfigured = "config";
    public static final String vHTTP = "send over network";
    public static final String vFile = "save as a file";

    public static final String kProfile = "profile";
    public static final String [] vProfile = {"slow walker", "walker", "biker", "driver"};

    public static final String kAutoPause = "autoPause";

    /**
     * the unique instance of Preferences
     */
    private static Preferences unique;
    /**
     * The name of the record store,
     * persistent storage of the parameters
     */
    private final String mRecordStoreName = "preferences";
    /**
     * hashtable
     * transient storage of the parameters
     */
    private Hashtable mHashtable;

    /**
     * Constructor
     */
    private Preferences() {
        mHashtable = new Hashtable();
        load();
    }

    /**
     * Factory method
     * @return a unique instance of <code>Preferences</code>.
     */
    public static synchronized Preferences getInstance() {
        if (unique == null) {
            unique = new Preferences();
        }
        return unique;
    }

    /**
     * Get the value of a parameter.
     * @param key the key of the parameter
     * @return the value of the parameter
     */
    public String get(String key) {
        return (String) mHashtable.get(key);
    }

    /**
     * Put the value of a parameter.
     * @param key the key of the parameter
     * @param value the value of the parameter
     */
    public void put(String key, String value) {
        if (value == null) {
            value = "";
        }
        mHashtable.put(key, value);
    }

    /**
     * Load the parameters from the persistent storage into the transient storage.
     */
    private void load() {
        RecordStore rs = null;
        RecordEnumeration re = null;

        try {
            rs = RecordStore.openRecordStore(mRecordStoreName, true);
            re = rs.enumerateRecords(null, null, false);
            while (re.hasNextElement()) {
                byte[] raw = re.nextRecord();
                String pref = new String(raw);
                // Parse out the name.
                int index = pref.indexOf('|');
                String name = pref.substring(0, index);
                String value = pref.substring(index + 1);
                put(name, value);
            }
        } catch (RecordStoreException rse) {
            rse.printStackTrace();
        } finally {
            if (re != null) {
                re.destroy();
            }
            try {
                if (rs != null) {
                    rs.closeRecordStore();
                }
            } catch (RecordStoreException rse) {
                rse.printStackTrace();
            }
        }
    }

    /**
     * Save the parameters from the transient storage into the persistent storage.
     */
    public void save() {
        RecordStore rs = null;
        RecordEnumeration re = null;
        try {
            rs = RecordStore.openRecordStore(mRecordStoreName, true);
            re = rs.enumerateRecords(null, null, false);

            // First remove all records, a little clumsy.
            while (re.hasNextElement()) {
                int id = re.nextRecordId();
                rs.deleteRecord(id);
            }

            // Now save the preferences records.
            Enumeration keys = mHashtable.keys();
            while (keys.hasMoreElements()) {
                String key = (String) keys.nextElement();
                String value = get(key);
                String pref = key + "|" + value;
                byte[] raw = pref.getBytes();
                rs.addRecord(raw, 0, raw.length);
            }
        } catch (RecordStoreException rse) {
            rse.printStackTrace();
        } finally {
            if (re != null) {
                re.destroy();
            }
            try {
                if (rs != null) {
                    rs.closeRecordStore();
                }
            } catch (RecordStoreException rse) {
                rse.printStackTrace();
            }
        }
    }
}
